   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.io.IOException;
   import java.net.URISyntaxException;
   import java.util.Arrays;

/**
 * This class is the GUI for getting inputs from user to fill out fields for an iCal file.  
 * It uses a left column with clickable buttons that all pop out a window with various ways to input information.
 * The right column displays the users inputs as they fill them in.  The bottom has reset and save buttons.
 * Error checking is done in each field to ensure proper inputs are received.
 * @author ICS 414 - Upgrade Project
 */

  
   public class UserGUI extends JFrame{
   
      private JPanel content;
   
      private JButton inputTimeZone;
      private JButton inputStartTime;
      private JButton inputEndTime;
      private JButton inputClassification;
      private JButton inputPath;
      private JButton inputComment;
      private JButton inputLocation;
      private JButton inputResources;
      private JButton inputRecurring;
      private JButton inputTypeRecurring;
      private JButton inputEndDateRecurring;
      private JButton emailOption;
      private JButton directory;
   
      private JLabel outputTimeZone;
      private JLabel outputStartTime;
      private JLabel outputEndTime;
      private JLabel outputClassification;
      private JLabel outputPath;
      private JLabel outputComment;
      private JLabel outputLocation;
      private JLabel outputResources;
      private JLabel outputRecurring;
      private JLabel outputTypeRecurring;
      private JLabel outputEndDateRecurring;
      private JLabel emailOption2;
      private JLabel directoryOutput;
   
      private JButton reset;
      private JButton save;
   
      private Event myEvent;
      private String name;
   
   /**
   * GUI Constructor - Sets up top, center, and bottom JPanels.
   * Top has simple constructions including the filename as input by the user.
   * Center contains a grid with left including all input buttons and output text displays.
   * Bottom has two control buttons 'reset' and 'save'.
   */
      public UserGUI(){
      
         myEvent = new Event();
      
      // initialize frame	
         this.content = new JPanel();
         content.setLayout(new BorderLayout());
      
      // top		
         JLabel top = new JLabel();
         content.add(top, BorderLayout.PAGE_START);
      
      // center
         JPanel center = new JPanel();
         center.setLayout(new GridLayout(13,3));
      
         inputTimeZone = new JButton("Time Zone");
         inputStartTime = new JButton("Start Time");
         inputEndTime = new JButton("End Time");
         inputClassification = new JButton("Classification");
         inputPath = new JButton("Save File Path");
         inputComment = new JButton("Comment");
         inputLocation = new JButton("Location");
         inputResources = new JButton("Resources");
         inputRecurring = new JButton("Recurring");
         inputTypeRecurring = new JButton("Type of Recurring");
         inputEndDateRecurring = new JButton("End Date For Recursion");
         emailOption = new JButton("Email ICS file");
         directory = new JButton("Create Directory");
      
         inputTimeZone.addActionListener(new MyListener());
         inputStartTime.addActionListener(new MyListener());
         inputEndTime.addActionListener(new MyListener());
         inputClassification.addActionListener(new MyListener());
         inputPath.addActionListener(new MyListener());
         inputComment.addActionListener(new MyListener());
         inputLocation.addActionListener(new MyListener());
         inputResources.addActionListener(new MyListener());
         inputRecurring.addActionListener(new MyListener());
         inputTypeRecurring.addActionListener(new MyListener());
         inputEndDateRecurring.addActionListener(new MyListener());
         emailOption.addActionListener(new MyListener());
         directory.addActionListener(new MyListener());
      
         outputTimeZone = new JLabel("Required");
         outputStartTime = new JLabel("Required");
         outputEndTime = new JLabel("Required");
         outputClassification = new JLabel("Required");
         outputPath = new JLabel("Required");
         outputComment = new JLabel("Optional");
         outputLocation = new JLabel("Optional");
         outputResources = new JLabel("Optional");
         outputRecurring = new JLabel("Optional");
         outputTypeRecurring = new JLabel("Optional");
         outputEndDateRecurring = new JLabel("Optional");
         emailOption2 = new JLabel("Optional");
         directoryOutput = new JLabel("Optional");
      
      //set colors to help user distinguish between required and optional fields		
      
         outputTimeZone.setForeground(Color.red);
         outputStartTime.setForeground(Color.red);
         outputEndTime.setForeground(Color.red);
         outputClassification.setForeground(Color.red);
         outputPath.setForeground(Color.red);
         outputComment.setForeground(Color.green);
         outputLocation.setForeground(Color.green);
         outputResources.setForeground(Color.green);
         outputRecurring.setForeground(Color.green);
         outputTypeRecurring.setForeground(Color.green);
         outputEndDateRecurring.setForeground(Color.green);
         emailOption2.setForeground(Color.green);
         directoryOutput.setForeground(Color.green);
      
      
         String parser = "      ..............................................................      "; //goes into center of grid separating inputs from outputs
      
         center.add(inputTimeZone);
         center.add(new JLabel(parser));		
         center.add(outputTimeZone);
      
         center.add(inputStartTime);
         center.add(new JLabel(parser));		
         center.add(outputStartTime);
      
         center.add(inputEndTime);
         center.add(new JLabel(parser));		
         center.add(outputEndTime);
      
         center.add(inputClassification);
         center.add(new JLabel(parser));		
         center.add(outputClassification);
         
         center.add(inputPath);
         center.add(new JLabel(parser));
         center.add(outputPath);
      
         center.add(inputComment);
         center.add(new JLabel(parser));		
         center.add(outputComment);		
      
         center.add(inputLocation);
         center.add(new JLabel(parser));		
         center.add(outputLocation);
      
         center.add(inputResources);
         center.add(new JLabel(parser));
         center.add(outputResources);
      
         center.add(inputRecurring);
         center.add(new JLabel(parser));		
         center.add(outputRecurring);
      	
         center.add(inputTypeRecurring);
         center.add(new JLabel(parser));		
         center.add(outputTypeRecurring);
      
         center.add(inputEndDateRecurring);
         center.add(new JLabel(parser));
         center.add(outputEndDateRecurring);
         
         center.add(emailOption);
         center.add(new JLabel(parser));
         center.add(emailOption2);
      
         center.add(directory);
         center.add(new JLabel(parser));
         center.add(directoryOutput);
      	
         content.add(center, BorderLayout.CENTER);
      
      // bottom
         JPanel bottom = new JPanel();
         bottom.setLayout(new FlowLayout());
      
         reset = new JButton("Reset");		
         save = new JButton("Save");
      
         reset.addActionListener(new MyListener());		
         save.addActionListener(new MyListener());
      
         bottom.add(reset);
         bottom.add(save);
      
         content.add(bottom, BorderLayout.PAGE_END);
      
      // finalize frame		
         this.setContentPane(content);
         this.pack();
         this.setLocationRelativeTo(null);
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.setTitle("ICS 414 - Project upgrade");
      
      // get user input for filename
         //preset to default to stop error of no names
         name = JOptionPane.showInputDialog("Please enter a name for your event:", "default");
         top.setText("Please fill in fields to create " + name + ".ics file");
         myEvent.setName(name);
        
      } //end of constructor    
   
   //methods for buttons
   /**
    * This method executes when timeZone JButton is pressed.
    * It sets up a selection of 25 different time zones for the user to choose from.
    * Then it sends the String input information (+12 to -12) to Event Object.
    */
      private void pressTimeZone(){
         Object [] tZones = {
               "GMT+12 Fiji",
               		"GMT+11 Solomon Islands",
               		"GMT+10 Guam",
               		"GMT+09 Japan",
               		"GMT+08 Hong Kong, China",
               		"GMT+07 Thailand",
               		"GMT+06 Bangladesh",
               		"GMT+05 Uzbekistan",
               		"GMT+04 Armenia",
               		"GMT+03 Kuwait",
               		"GMT+02 Lebanon",
               		"GMT+01 Germany",
               		"GMT+00 Iceland",
               		"GMT-01 Portugal",
               		"GMT-02 South Georgia",
               		"GMT-03 Argentina",
               		"GMT-04 Puerto Rico",
               		"GMT-05 Bahamas",
               		"GMT-06 Easter Island",
               		"GMT-07 Alberta, Canada",
               		"GMT-08 Los Angeles",
               		"GMT-09 Alaska",
               		"GMT-10 Hawaii",
               		"GMT-11 American Samoa",
               		"GMT-12 Baker Island"
               		};
         String input = (String) JOptionPane.showInputDialog(this, "Please select a time zone", "Selection Screen", 								JOptionPane.INFORMATION_MESSAGE, null, tZones, tZones[22]);
         if(input == null){
            return;
         }
         myEvent.setTimeZone(input.substring(3,6));	
         outputTimeZone.setText(input);
      }
    /**
     * This method executes when startTime JButton is pressed.
     * It gives the user a pop-up with 5 input boxes for month, date, year, hour, and minute.
     * It keeps user on the pop-up until a valid date is given or cancel button is pressed.
     */
      private void pressStartTime(){
      
         JPanel dateTime = new JPanel();
      
         JTextField monthField = new JTextField("MM",2);
         JTextField dateField = new JTextField("DD",2);
         JTextField yearField = new JTextField("YYYY",4);
         JTextField hourField = new JTextField("HH",2);
         JTextField minField = new JTextField("MM",2);
      
         monthField.select(0,2);
         dateField.select(0,2);
         yearField.select(0, 4);
         hourField.select(0,2);
         minField.select(0, 2);
      		
         dateTime.add(monthField);
         dateTime.add(new JLabel(" / "));
         dateTime.add(dateField);
         dateTime.add(new JLabel(" / "));
         dateTime.add(yearField);
         dateTime.add(new JLabel("   -   "));		
         dateTime.add(hourField);
         dateTime.add(new JLabel(" : "));
         dateTime.add(minField);
      
         boolean errorCheck = true;
      
         while(errorCheck){
            int reply = JOptionPane.showConfirmDialog(this, dateTime, "Please enter date and time", JOptionPane.OK_CANCEL_OPTION);
         
            if(reply == JOptionPane.CANCEL_OPTION){
               errorCheck = false;
            }
            else{
               try{
                  int month = Integer.parseInt(monthField.getText());
                  int date = Integer.parseInt(dateField.getText());
                  int year = Integer.parseInt(yearField.getText());
                  int hour = Integer.parseInt(hourField.getText());
                  int min = Integer.parseInt(minField.getText());
               
                  myEvent.setStart(year,month,date,hour,min);
                  errorCheck = false;
                  outputStartTime.setText(myEvent.guiStart());
               
               } 
                  catch (IllegalArgumentException e){
                     JOptionPane.showMessageDialog(this, "Please re-enter a valid date & time.");
                  }
            }
         } //end loop
      }
    /**
     * This method executes when endTime JButton is pressed.
     * It gives the user a pop-up with 5 input boxes for month, date, year, hour, and minute.
     * It keeps user on the pop-up until a valid date is given or cancel button is pressed.
     */
      private void pressEndTime(){
      
         JPanel dateTime = new JPanel();
      
         JTextField monthField = new JTextField("MM",2);
         JTextField dateField = new JTextField("DD",2);
         JTextField yearField = new JTextField("YYYY",4);
         JTextField hourField = new JTextField("HH",2);
         JTextField minField = new JTextField("MM",2);
      
         monthField.select(0,2);
         dateField.select(0,2);
         yearField.select(0, 4);
         hourField.select(0,2);
         minField.select(0, 2);
      
         dateTime.add(monthField);
         dateTime.add(new JLabel(" / "));
         dateTime.add(dateField);
         dateTime.add(new JLabel(" / "));
         dateTime.add(yearField);
         dateTime.add(new JLabel("   -   "));		
         dateTime.add(hourField);
         dateTime.add(new JLabel(" : "));
         dateTime.add(minField);
      
         boolean errorCheck = true;
      
         while(errorCheck){
            int reply = JOptionPane.showConfirmDialog(this, dateTime, "Please enter date and time", JOptionPane.OK_CANCEL_OPTION);
         
            if(reply == JOptionPane.CANCEL_OPTION){
               errorCheck = false;
            }
            else{
               try{
                  int month = Integer.parseInt(monthField.getText());
                  int date = Integer.parseInt(dateField.getText());
                  int year = Integer.parseInt(yearField.getText());
                  int hour = Integer.parseInt(hourField.getText());
                  int min = Integer.parseInt(minField.getText());
               
                  myEvent.setEnd(year,month,date,hour,min);
                  errorCheck = false;
                  outputEndTime.setText(myEvent.guiEnd());
               
               } 
                  catch (IllegalArgumentException e){
                     JOptionPane.showMessageDialog(this, "Please re-enter a valid date & time.");
                  }
            }
         }
      }
    
    /**
     * This method executes when Classification JButton is pressed.
     * It gives the user a scroll down choice menu.
     * It allows the user to set the file to be public, private or confidential.
     * The default is set public and must be clicked.
     */
      private void pressClassification(){
         Object[] options = {"PUBLIC", "PRIVATE", "CONFIDENTIAL"};
         String input = (String) JOptionPane.showInputDialog(this, "Please select a classification", "Selection Screen", 								JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
         if(input == null){
            return;
         }
         outputClassification.setText(input);
         myEvent.setClassification(input);
      }
      
      /**
       * This method executes when Location JButton is pressed.
       * It gives the user a text field to write any comments they may want to put with the file.
       * It is a optional field and will be left blank if there is no input.
       */
      private void pressPath(){
        	//This option is for a non prefilled type area
        	//This only reason for this would be that you dont want a default path to be saved.
            //String input = JOptionPane.showInputDialog(this,"Enter a save path: (i.e. \\Users\\Name\\Desktop\\)");
        	//To speed up the save process i have it setup so that the user can still erase the pre entered
        	//save destination and change it to their own but its there as an example of what the format should be
         String input = JOptionPane.showInputDialog("Enter a save path: (example shown below)", "\\Users\\Micah Hwang\\Desktop\\");
           
         if(input == null){
            return;
         }
         outputPath.setText(input);
         myEvent.setPath(input);
      }  
   	  
      private void pressDirectory(){
         String input = JOptionPane.showInputDialog("Please enter directory name","\\Enter Name Here\\");
         if(input == null){
            return;
         }
         directoryOutput.setText(input);
         myEvent.setDirectory(input);
      }
    
    
    
    /**
     * This method executes when Comment JButton is pressed.
     * It gives the user a text field to write any comments they may want to put with the file.
     * It is a optional field and will be left blank if there is no input.
     */
    
      private void pressComment(){
         String input = JOptionPane.showInputDialog(this,"Please enter comment");
         if(input == null){
            return;
         }
         outputComment.setText(input);
         myEvent.setComment(input);
      }
    /**
     * This method executes when Location JButton is pressed.
     * It gives the user a text field to write any comments they may want to put with the file.
     * It is a optional field and will be left blank if there is no input.
     */
      private void pressLocation(){
         String input = JOptionPane.showInputDialog(this,"Please enter location");
         if(input == null){
            return;
         }
         outputLocation.setText(input);
         myEvent.setLocation(input);
      }
    
    /**
     * This method executes when Resource JButton is pressed.
     * It gives the user a text field to write any comments they may want to put with the file.
     * It is a optional field and will be left blank if there is no input.
     */
    
      private void pressResources(){
         String input = JOptionPane.showInputDialog(this,"Please enter resources");
         if(input == null){
            return;
         }
         outputResources.setText(input);
         myEvent.setResources(input);
      }
    
    /**
     * This method executes when Recurring JButton is pressed.
     * It gives the user a check box menu of the week.
     * Allows the user to select a day/days that they want their event to recur.  
     * It is a optional field and will be left blank if there is no input.
     */
    
      private void pressRecurring(){
      
         JPanel recurring = new JPanel();
         boolean isRecur = false;
         JCheckBox [] boxDays = new JCheckBox [7];
         String [] days = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
         boolean[] repeatDays = new boolean[7];
      
         for(int i = 0; i < 7; i++){
            boxDays[i] = new JCheckBox(days[i]);
            recurring.add(boxDays[i]);
         }
      
         int reply = JOptionPane.showConfirmDialog(this, recurring, "Repeat Every:", JOptionPane.OK_CANCEL_OPTION);
      		
         if(reply == JOptionPane.OK_OPTION){
            isRecur = false;
            for(int i = 0; i < 7; i++){
               repeatDays[i] = boxDays[i].isSelected();
               isRecur = isRecur || boxDays[i].isSelected();
            }
         }
         else{
            isRecur = false;
         }
         myEvent.setRecurring(isRecur, repeatDays);
         outputRecurring.setText(myEvent.guiRecurring());
      }
   /**
   *this method will set the type of recursion the user wants
   *choices will be daily weekly monthly or yearly
   *after selection is made the recursion end date is chosen below, otherwise 
   *without an option to end it will continue forever. 
   */
      private void pressTypeRecurring(){
         Object[] options = {"DAILY", "WEEKLY", "MONTHLY", "YEARLY"};
         String input = (String) JOptionPane.showInputDialog
             			(this, "Please select a Type of Recursion", "Selection Screen", 								JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
         if(input == null){
            return;
         }
         outputTypeRecurring.setText(input);
         myEvent.setTypeRecur(input);
      }	
   	
    /**
    *this method is if End date for recursion is pressed.
    * it always the recursion to end on a certain date.
    */
    
      private void pressEndDateRecurring(){
      
         JPanel dateTime = new JPanel();
      
         JTextField monthField = new JTextField("MM",2);
         JTextField dateField = new JTextField("DD",2);
         JTextField yearField = new JTextField("YYYY",4);
         JTextField hourField = new JTextField("HH",2);
         JTextField minField = new JTextField("MM",2);
      
         monthField.select(0,2);
         dateField.select(0,2);
         yearField.select(0, 4);
         hourField.select(0,2);
         minField.select(0, 2);
      
         dateTime.add(monthField);
         dateTime.add(new JLabel(" / "));
         dateTime.add(dateField);
         dateTime.add(new JLabel(" / "));
         dateTime.add(yearField);
         dateTime.add(new JLabel("   -   "));		
         dateTime.add(hourField);
         dateTime.add(new JLabel(" : "));
         dateTime.add(minField);
      
         boolean errorCheck = true;
      
         while(errorCheck){
            int reply = JOptionPane.showConfirmDialog(this, dateTime, 
               		"Please enter date and time", JOptionPane.OK_CANCEL_OPTION);
         
            if(reply == JOptionPane.CANCEL_OPTION){
               errorCheck = false;
            }
            else{
               try{
                  int month = Integer.parseInt(monthField.getText());
                  int date = Integer.parseInt(dateField.getText());
                  int year = Integer.parseInt(yearField.getText());
                  int hour = Integer.parseInt(hourField.getText());
                  int min = Integer.parseInt(minField.getText());
               
                  myEvent.setEndRecur(year,month,date,hour,min);
                  errorCheck = false;
                  outputEndDateRecurring.setText(myEvent.guiEndRecur());
               
               } 
                  catch (IllegalArgumentException e){
                     JOptionPane.showMessageDialog(this, "Please re-enter a valid date & time.");
                  }
            }
         }
      }
    
    /**
     * This method executes when Reset JButton is pressed.
     * It reset the program, If feels that they want to change the whole thing.
     */
    
      private void pressReset(){
         outputTimeZone.setText("Required");
         outputStartTime.setText("Required");
         outputEndTime.setText("Required");
         outputClassification.setText("Required");
         outputPath.setText("Required");
         outputComment.setText("Optional");
         outputLocation.setText("Optional");
         outputResources.setText("Optional");
         outputRecurring.setText("Optional");
         outputTypeRecurring.setText("Optional");
         outputEndDateRecurring.setText("Optional");
         emailOption2.setText("Optional");
         directoryOutput.setText("Optional");
      
         myEvent.reset();
      
      }
    
   	/**
     * This method executes when save JButton is pressed.
     * It saves the file and writes the file into the eclipse work space folder.
     */
   	
      private void pressSave(){
         if(outputTimeZone.getText().equals("Required") || outputStartTime.getText().equals("Required") ||
         	 outputEndTime.getText().equals("Required") || outputClassification.getText().equals("Required")){
            JOptionPane.showMessageDialog(this, "Please fill in all Required fields.", "alert", JOptionPane.ERROR_MESSAGE);
         }
         else if(!myEvent.valiDate()){
            JOptionPane.showMessageDialog(this,
                "End date/end must be on or after start date/time.","Alert", JOptionPane.WARNING_MESSAGE);
         }
         else if(outputEndDateRecurring.getText().equals("Optional") &&
         	 outputTypeRecurring.getText().equals("DAILY")){
            JOptionPane.showMessageDialog(this,
                "The recursion option has been selected, please make sure to enter a recursion end date.",
                "Alert", JOptionPane.WARNING_MESSAGE);
         
         }
         else if(outputEndDateRecurring.getText().equals("Optional") &&
         	 outputTypeRecurring.getText().equals("WEEKLY")){
            JOptionPane.showMessageDialog(this,
                "The recursion option has been selected, please make sure to enter a recursion end date.",
                "Alert", JOptionPane.WARNING_MESSAGE);
         
         }
         else if(outputEndDateRecurring.getText().equals("Optional") &&
         	 outputTypeRecurring.getText().equals("MONTHLY")){
            JOptionPane.showMessageDialog(this,
                "The recursion option has been selected, please make sure to enter a recursion end date.",
                "Alert", JOptionPane.WARNING_MESSAGE);
         
         }
         else if(outputEndDateRecurring.getText().equals("Optional") &&
         	 outputTypeRecurring.getText().equals("YEARLY")){
            JOptionPane.showMessageDialog(this,
                "The recursion option has been selected, please make sure to enter a recursion end date.",
                "Alert", JOptionPane.WARNING_MESSAGE);
         
         }
         else {
            ICSWriter.writeMe(myEvent);
            JOptionPane.showMessageDialog(this,"File \"" + name + ".ics\" created","Complete", JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
         }
      }	
      
   /**
       * This method executes when save JButton is pressed.
       * It is an option for the user to send the .ics file through email.
      * @throws URISyntaxException 
      * @throws IOException 
       */
      
      private void pressEmailOption() throws IOException, URISyntaxException {
         String input = JOptionPane.showInputDialog(this,"Please enter an email address");
         if(input == null){
            return;
         }
         String input2 = JOptionPane.showInputDialog(this,"Please enter an email subject");
         if(input2 == null){
            return;
         }
         EmailOption.mailto(Arrays.asList(input)
              , input2, "Attached is the .ics file.\n");
      	
      }
    
    /**
     * This class is the ActionListner.
     * It allows the methods to be called when the button is clicked on.
     */
    
      class MyListener implements ActionListener {
         public void actionPerformed(ActionEvent e) {
                 
            JButton pressedButton = (JButton) e.getSource();
         
            if(pressedButton == inputTimeZone){
               pressTimeZone();
            }
            if(pressedButton == inputStartTime){
               pressStartTime();
            }
            if(pressedButton == inputEndTime){
               pressEndTime();
            }
            if(pressedButton == inputClassification){
               pressClassification();
            }
            if(pressedButton == inputPath){
               pressPath();
            }
            if(pressedButton == directory){
               pressDirectory();
            }
            if(pressedButton == inputComment){
               pressComment();
            }
            if(pressedButton == inputLocation){
               pressLocation();
            }
            if(pressedButton == inputResources){
               pressResources();
            }
            if(pressedButton == inputRecurring){
               pressRecurring();
            }     
            if(pressedButton == inputTypeRecurring){
               pressTypeRecurring();
            }       
            if(pressedButton == inputEndDateRecurring){
               pressEndDateRecurring();
            }
            if(pressedButton == emailOption){
               try {
                  pressEmailOption();
               } 
                  catch (IOException e1) {
                     e1.printStackTrace();
                  } 
                  catch (URISyntaxException e1) {
                     e1.printStackTrace();
                  }
            }
            if(pressedButton == reset){
               pressReset();
            }
            if(pressedButton == save){
               pressSave();
            }	
         }
      }
   }